package com.qf.consumer.controller;

import com.qf.common.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;

@RestController
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/test4")
    public ResultVo test4(){
        // 调用redis微服务的投票接口
        String url = "http://service-redis/vote";

        // 准备请求体中 的数据 。格式要求：x-www-form-urlencoded , 既 phone=13355556666&name=zhangsan
        // 创建 代表Http请求的对象
        // 创建请求头对象和请求体对象

        LinkedMultiValueMap<String, String> body = new LinkedMultiValueMap<>();
        body.add("phone","13355556666");
        body.add("name","zhangsan");

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body,httpHeaders);

//        HashMap<String, String> body = new HashMap<>();
//        body.put("phone","13355556666");
//        body.put("name","zhangsan");

        ResultVo resultVo = restTemplate.postForObject(url, body, ResultVo.class);
        return resultVo;
    }

    @GetMapping("/test3")
    public ResultVo test3(){
        // 调用redis微服务的投票接口
        String url = "http://service-redis/vote?phone={phone}&name={name}";

        // 参数2：请求体中的数据，可以为null
        // 最后的变长参数会用来替换url中的占位符 {phone} 和 {name}
        ResultVo resultVo = restTemplate.postForObject(url, null, ResultVo.class,"13588889999","lisi");
        return resultVo;
    }


    @GetMapping("/test1")
    public String test1(){
        String msg = "consumer";
        String url = "http://service-provider/test1?msg="+msg;
        // 调用微服务 service-provider
        String result = restTemplate.getForObject(url, String.class);
        return result + ": from consumer";
    }

    @GetMapping("/test2")
    public ResultVo test2(){
        String username = "lisi";
        Integer userid = 100;
        Integer time = 60;

        String url = "http://service-token/create?username="+username+"&userid="+userid+"&time="+time;
        // 调用微服务 service-provider
//        String result = restTemplate.getForObject(url, String.class);
        ResultVo vo = restTemplate.getForObject(url, ResultVo.class);

        return vo;
    }


}
